from django.contrib.auth.hashers import make_password
from django.shortcuts import render,redirect
from .models import MyUser
from django.contrib.auth.views import auth_login,auth_logout,login_required
from .forms import RegisterForms
# Create your views here.
def login(request):
    error = None
    if request.method == "POST":
        username = request.POST.get("username")
        password = request.POST.get("password")
        user = MyUser.objects.filter(username=username).first()
        if user:
            if user.check_password(password):
                auth_login(request, user)
                return redirect(to="/")
            else:
                error = "密码错误"
        else:
            error = "用户名不存在"

    return render(request,"user/login.html",context=({
        "error":error
    }))



def register(request):
    rgf = RegisterForms()
    if request.method == "POST":
        rgf = RegisterForms(request.POST)
        # 判断输入的表单数据是否有效
        # 只会判断数据模型中的数据和格式，因此不会判断密码是否一致，需要我们自己判断
        if rgf.is_valid():
            # 通过表单模型的 cleaned_data 获取表单的数据
            password = rgf.cleaned_data.pop("password")
            # 为了保持与模板数据一致，删除password2
            password2 = rgf.cleaned_data.pop("password2")
            if password == password2:
                # 获取对象，但是不保存数据库，节省性能，还要加密密码
                user = rgf.save(commit=False)
                # 加密密码
                user.password = make_password(password)

                # 保存数据库
                user.save()
                # 同步前台
                auth_login(request, user)
                return redirect(to="/")
            else:
                rgf.errors.update({
                    "password":"密码不一致"
                })
    return render(request,"user/register.html",context=({
        "rgf":rgf
    }))
def center(request):
    return render(request,"user/center.html")




def logout(request):
    auth_logout(request)
    return render(request,"main/index.html")
